package com.hackordie.daos;

import org.springframework.dao.EmptyResultDataAccessException;

import com.hackordie.commons.authorities.User;
import com.hackordie.daos.mappers.UserMapper;

public class UserDao extends ACommonDao<User> {

	@Override
	public boolean create(final User entity) {
	    	    
	    //insertamos un nuevo user, si tenemos exito, creamos un nuevo profile con el mismo id
		String SQL = "INSERT INTO users (name, " +
				                        "password, " +
				                        "email, " +	
				                        "enabled, " +
				                        "activationCode, " +
				                        "idRole, " +
				                        "computerType) " +
				      "VALUES ('" + entity.getUserName() + "', " +
				              "'" + entity.getUserPassword() + "', " +
				              "'" + entity.getEmail() + "', " +
				                    entity.isEnabled() + ", " +
				              "'" + entity.getActivationCode() + "', " +
				                    2 + ", " +  //role inicial es user
				                    entity.getComputerType() + ")";    
				                    		
		
		if(jdbcTemplate.update(SQL) == 1) {		    
		    //nuevo profile creado como resultado de un trigger en la BD
		    return true;
		}
		return false;
	}

	@Override
	public boolean delete(final int idUser) {
		final String SQL = "DELETE FROM users WHERE idUser = ?";
		jdbcTemplate.update(SQL, idUser);
		return true;
	}

	public boolean delete(String userName) {
		final String SQL = "DELETE FROM users WHERE name = '" + userName + "'";
		jdbcTemplate.update(SQL);
		return true;
	}

	@Override  //TODO aqui quedan campos por actualizar
	public boolean update(final User entity) {
		final String SQL = "UPDATE users " +
				           "SET name = '" + entity.getUserName() + "', " +
				                "password = '" + entity.getUserPassword() + "', " +
				                "enabled = " + entity.isEnabled() + ", " +	
				                "idRole = " + entity.getRole() + ", " +
				                "money = " + entity.getMoney() + " " +
				           "WHERE idUser = " + entity.getId();
		jdbcTemplate.update(SQL);
		return true;
	}

	@Override
	public User[] getAll() {
		final String SQL = "SELECT * FROM users";
		User users[] = jdbcTemplate.query(SQL, new UserMapper()).toArray(new User[] {});
		
		for(int i = 0; i < users.length; i++) {
		    users[i].setRoleName(getUserRoleString(users[i].getRole()));
		}
		
		return users;
	}

	public User[] getByRange(int first, int last) {
		final String SQL = "SELECT * FROM users LIMIT ?,?";
		User users[] = jdbcTemplate.query(SQL, new UserMapper(), first, last).toArray(new User[] {});
		
		for(int i = 0; i < users.length; i++) {
            users[i].setRoleName(getUserRoleString(users[i].getRole()));
        }
        
        return users;
	}

	public int countAll() {
		final String SQL = "Select COUNT(idUser) FROM users";
		return jdbcTemplate.queryForObject(SQL, Integer.class);
	}

	@Override
	public User get(int idUser) {
		final String SQL = "SELECT * FROM users WHERE idUser = ?";
		User user = jdbcTemplate.queryForObject(SQL, new UserMapper(), idUser);
		
		user.setRoleName(getUserRoleString(user.getRole()));
		
		return user;
	}

	public User get(String userName) {
		final String SQL = "SELECT * FROM users WHERE name = ?";		
		User user = jdbcTemplate.queryForObject(SQL, new UserMapper(), userName);
		
		user.setRoleName(getUserRoleString(user.getRole()));
		
		return user;
	}
	
	private String getUserRoleString(int idRole) {
	    final String SQL = "SELECT name FROM roles WHERE idRole = " + idRole;
	    //TODO utilizar HackOrDieExceptions
	    try {
	    return jdbcTemplate.queryForObject(SQL, String.class);
	    
	    } catch (EmptyResultDataAccessException e ) {
	        return "unknow role";
	    } catch (Exception e) {
	        return "unknow Error";
	    }	   
	}

}
